package com.seafwg.junior;

import com.seafwg.junior.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author seafwg
 * @Date 2022/3/14 10:50 上午
 * @Version 1.0
 * @description xxx
 */

public class test {

    private SqlSession sqlSession;

    @Before
    public void before() throws IOException {
        // 加载核心配置文件：通过ibatis提供的Resources.getResourceAsStream()方法加载sql核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        // 获得sql的工厂对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        // SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        // 获得sqlSession对象
        sqlSession = sqlSessionFactory.openSession();
    }

    @After
    public void after() {
        sqlSession.commit(); // 提交事物: 增删改设计数据库数据的变化，都需要添加事物
        sqlSession.close();
    }

    // 查询所有用户数据：
    @Test
    public void test() {
        // 通过sqlSession的sql会话对象调用查询方法，通过mapp.xml文件的命名空间+id调用sql
        List<User> userList = sqlSession.selectList("userMapper.findAll");
        System.out.println(userList);
    }

    // 新增用户
    @Test
    public void tAddUser() {
        User user = new User();
        user.setUsername("seafwg");
        user.setPassword("123456");
        int insert = sqlSession.insert("userMapper.add", user);
        System.out.println(insert);
    }

    // 删除用户
    @Test
    public void tDelUser() {
        User user = new User();
        user.setId(2);
        int delete = sqlSession.delete("userMapper.delUser", user);
        System.out.println(delete);
    }

    // 修改用户
    @Test
    public void tUpdateUser() {
        User user = new User();
        user.setId(3);
        user.setUsername("seafwg");
        user.setPassword("111222");
        int update = sqlSession.update("userMapper.updateUser", user);
        System.out.println(update);
    }
}
